package jp.co.cos.ittrick.channel.controller.admin;

import java.util.ArrayList;
import java.util.List;

import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Text;

public class PageUpdateController extends Controller {

    private PageService pageService;
    private ChapterService chapterService;

    public PageUpdateController() {
        pageService = new PageService();
        chapterService = new ChapterService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");
        String page = asString("page");
        String chapter = asString("chapter");
        String name = asString("pageName");
        String index = asString("index");
        String content = asString("content");
        String keyWords = asString("keyWord");
        String description = asString("description");

        List<String> keyWordList = getStringList(keyWords);

        ChapterModel chapterModel = chapterService.getChapterByKey(Integer.valueOf(chapter));

        // Modelの設定
        PageModel model = pageService.getPageByKey(Integer.valueOf(page));
        if(model != null) {
            model.setName(name);
            model.setIndex(Integer.valueOf(index));
            model.setKeyWordList(keyWordList);
            model.setDescription(description);
            model.getChapterModelRef().setModel(chapterModel);
            model.setContent(new Text(content));

            // Insert
            pageService.update(model);
        }

        return redirect("/admin/pageEdit?channel=" + channel + "&chapter=" + chapter + "&page=" + page);
    }


    private List<String> getStringList(String texts) {

        List<String> stringList = new ArrayList<String>();
        if(texts != null && texts != "") {
            String[] amznWdgtAsinsTmp = texts.split(",");
            for(String txt: amznWdgtAsinsTmp) {
                if(!txt.isEmpty()) {
                    stringList.add(txt);
                }
            }
        }
        return stringList;
    }
}
